import {
  generateCrudPage,
  headerToolbar,
  bulkActions,
  listButtons,
  footerToolbar,
} from "./sys_columns.ts";
import { parse } from 'url';
import adminCrud from "./sys_admin_crud.ts";
import AdminUsers from "../models/AdminUsers.ts";
import AdminRole  from "../models/AdminRoles.ts";
import AdminRoleUsers  from "../models/AdminRoleUsers.ts";
import { sutando }  from "sutando";
import { successResponse, errorResponse } from "../../helpers.ts";
import bcrypt from "bcrypt";
import svgCaptcha from "svg-captcha"
const apiUrl = "/admin-api/system/admin_users";
//const tableName = 'admin_users'
export async function grid() {
  const list = {
    apiUrl: apiUrl,
    bulkActions: await bulkActions(), //批量操作
    footerToolbar: await footerToolbar(), //底部工具栏
    headerToolbar: await headerToolbar(apiUrl, form), //头部工具栏
    filter: await filter(), //筛选
    itemCheckableOn: "this.id != 1",
    columns: [
      { name: "id", label: "ID" },
      {
        name: "avatar",
        label: "头像",
        type: "avatar",
        src: "${avatar}",
      },
      { name: "username", label: "用户名", searchable: true },
      { name: "name", label: "姓名" },
      {
        name: "roles",
        label: "角色",
        type: "each",
        items: {
          type: "tag",
          label: "${name}",
          className: "my-1",
        },
      },
      {
        name: "enabled",
        label: "状态",
        quickEdit: {
          type: "switch",
          mode: "inline",
          disabledOn: "${id == 1}",
          saveImmediately: true,
          onText: "启用",
          offText: "禁用",
        },
      },
      {
        name: "created_at",
        label: "创建时间",
        type: "datetime",
        sortable: true,
      },
      await listButtons({
        types: ["edit", "detail", "delete"],
        apiUrl: apiUrl,
        detail: detail,
        form: form,
        buttonsOptions: {
          delete: {
            disabledOn: "this.id === 1",
          },
        },
      }),
    ],
  };
  return await generateCrudPage(list);
}

//表单配置
async function form() {
  const roles = await AdminRole.query().select("id", "name").get();
  return [
    {
      type: "input-image",
      receiver: "/api/uploadImg",
      name: "avatar",
      label: "头像",
    },
    {
      type: "input-text",
      name: "username",
      label: "用户名",
      required: true,
    },
    {
      type: "input-text",
      name: "name",
      label: "姓名",
      required: true,
    },
    {
      type: "input-password",
      name: "password",
      label: "密码",
    },
    {
      type: "input-password",
      name: "confirm_password",
      label: "确认密码",
    },
    {
      type: "select",
      name: "roles",
      label: "角色",
      searchable: true,
      multiple: true,
      labelField: "name",
      valueField: "id",
      joinValues: false,
      extractValue: true,
      hiddenOn: "${id == 1}",
      options: roles,
    },
    {
      type: "switch",
      name: "enabled",
      label: "状态",
      onText: "启用",
      offText: "禁用",
      disabledOn: "${id == 1}",
      value: 1,
    },
  ];
}

  //详情配置
  async function detail() {
    return {
      title: "查看详情",
      body: {
        type: "form",
        body: [
          {
            type: "input-text",
            name: "username",
            label: "用户名",
            value: "${username}",
            disabled: true,
          },
          {
            type: "input-text",
            name: "name",
            label: "姓名",
            value: "${name}",
            disabled: true,
          },
        ],
      },
    };
  }

//筛选配置
async function filter() {
  return {
    title: "筛选",
    mode: "inline",
    controls: [
      { type: "input-text", name: "username", label: "用户名" },
      { type: "input-text", name: "name", label: "姓名" },
      { type: "submit", label: "查询", level: "primary" },
      { type: "reset", label: "重置" },
    ],
  };
}

export const SysUsersController = {
  async index(req, res) {
    try {
      const queryParams = parse(req.url, true).query;
      if (queryParams._replace === "1") {
        const list = await grid();
        return successResponse(res, {data: list});
      }
      const query = AdminUsers.query().with("roles");
      if (req.query.username) {
        query.where("username", "like", `%${req.query.username}%`);
      }
      if (req.query.name) {
        query.where("name", "like", `%${req.query.name}%`);
      }
      const list = await query.paginate(req.query.page, req.query.perPage);
      return successResponse(res, {data: list.items()});
    } catch (error) {
      console.error("获取用户列表失败:", error);
      return errorResponse(res, {msg: "服务器错误，请稍后重试"});
    }
  },

  async store(req, res) {
    const query = parse(req.url, true).query;
    if (query._action === "quickEditItem") {
      const { id, roles, ...params } = req.body;
      if (!params.username) {
        return errorResponse(res, {msg: "用户名不能为空！"});
      }
      if (!params.name) {
        return errorResponse(res, {msg: "姓名不能为空！"});
      }
      if (!params.password) {
        return errorResponse(res, {msg: "密码不能为空！"});
      }
      if (params.password) {
        params.password = await bcrypt.hash(params.password, 10);
      }
      return adminCrud.quickEditItem(req, res, AdminUsers, id, params);
    }
    return adminCrud.store(req, res, module);
  },
  async edit(req, res) {
    const { id } = req.params;
    if (!id) {
      return errorResponse(res, {msg: "无效的请求参数！"});
    }
    try {
      const roles = await AdminUsers.query().with("roles").find(id);
      const responseData = {
        status: 0,
        msg: "ok",
        data: roles,
      };
      return successResponse(res, {data: roles});
    } catch (error) {
      return errorResponse(res, {msg: "服务器错误！"});
    }
  },
  async update(req, res) {
    const { id } = req.params;
    const { roles, ...params } = req.body;
    if (!params.username) {
      return errorResponse(res, {msg: "用户名不能为空！"});
    }
    if (!params.name) {
      return errorResponse(res, {msg: "姓名不能为空！"});
    }
    if (!params.password) {
      return errorResponse(res, {msg: "密码不能为空！"});
    }

    if (Object.keys(params).length === 0) {
      return errorResponse(res, {msg: "无效的请求参数！"});
    }
    // 删除不该更新的字段
    delete params.created_at;
    delete params.updated_at;
    delete params.items;
    if (params.password) {
      params.password = await bcrypt.hash(params.password, 10);
    }
    const db = sutando.connection();
    try {
      await db.transaction(async (trx) => {
        // 更新用户数据
        const result = await AdminUsers.query()
          .transacting(trx)
          .where({ id })
          .update(params);
        if (!result) {
          // 如果没更新到数据，手动抛错，触发事务回滚
          throw new Error("保存失败！");
        }

        if (roles && roles.length > 0) {
          let roleUserPairs = [];
          if (roles[0].pivot) {
            roleUserPairs = roles.map((role) => ({
              user_id: id,
              role_id: role.id,
              created_at: new Date(),
              updated_at: new Date(),
            }));
          } else {
            // 如果是 [1, 2, 3]
            roleUserPairs = roles.map((roleId) => ({
              user_id: id,
              role_id: roleId,
              created_at: new Date(),
              updated_at: new Date(),
            }));
          }
          // 删除旧的角色关联
          await AdminRoleUsers.query()
            .transacting(trx)
            .where({ user_id: id })
            .delete();
          // 插入新的角色关联
          await AdminRoleUsers.query().transacting(trx).insert(roleUserPairs);
        }
      });

      // 如果事务执行成功
      return successResponse(res, {msg: "保存成功！"});
    } catch (error) {
      // 出错了
      return errorResponse(res, {msg: "服务器内部错误！"});
    }
  },

  async destroy(req, res) {
    return adminCrud.destroy(req, res, AdminUsers);
  },
 async  captcha (req, res){
    try {
      const captcha = svgCaptcha.create({
        size: 4,
        noise: 2,
        color: true,
        background: "#fff",
      });
  
      global.currentCaptcha = captcha.text.toLowerCase();
  
      res.type("svg");
      res.send(captcha.data);
    } catch (err) {
      console.error("生成验证码失败:", err);
      res.end(JSON.stringify({ error: "生成验证码失败" }));
    }
  }
};
